package service

import (
	"boy-go/modules/demo/model"
	"boy-go/modules/demo/repository"
	"boy-go/modules/demo/vo"
	"boy-go/pkg/request"
	"github.com/jinzhu/copier"
	"gorm.io/gorm"
)

func NewTSchoolService() TSchoolService {
	return &tSchoolService{
		TSchoolRepo: repository.NewTSchoolRepository(),
	}
}

type tSchoolService struct {
	TSchoolRepo *repository.TSchoolRepository
}

// GetById 根据id获取配置信息
func (s *tSchoolService) GetById(id int64) (*vo.TSchoolModel, error) {
	m, err := s.TSchoolRepo.GetById(id)
	if err != nil {
		return nil, err
	}
	rsp := new(vo.TSchoolModel)
	if err = copier.Copy(rsp, m); err != nil {
		return nil, err
	}
	subs, err := s.TSchoolRepo.ListTSchoolTagBySchoolId(id)
	if err == nil {
		subModels := make([]*vo.TSchoolTagModel, 0)
		for _, sub := range subs {
			subModel := new(vo.TSchoolTagModel)
			if err = copier.Copy(&subModel, sub); err != nil {
				continue
			}
			subModels = append(subModels, subModel)
		}
		rsp.TSchoolTagList = subModels
	}
	return rsp, nil
}

// List 获取学校表列表
func (s *tSchoolService) List(req *vo.QueryTSchoolReq, pageReq *request.PageRequest) (*vo.ListTSchoolRsp, error) {
	list, total, err := s.TSchoolRepo.List(req, pageReq)
	if err != nil {
		return nil, err
	}
	itemList := make([]*vo.TSchoolModel, 0)
	for _, v := range list {
		item := new(vo.TSchoolModel)
		if err := copier.Copy(item, &v); err != nil {
			continue
		}
		itemList = append(itemList, item)
	}
	return &vo.ListTSchoolRsp{
		List:  itemList,
		Total: total,
	}, nil
}

// Add 添加学校表
func (s *tSchoolService) Add(req *vo.AddTSchoolReq) (*vo.AddTSchoolRsp, error) {
	m := new(model.TSchool)
	err := copier.Copy(m, req)
	if err != nil {
		return nil, err
	}
	err = s.TSchoolRepo.DB.Transaction(func(tx *gorm.DB) error {
		if dbErr := tx.Model(&model.TSchool{}).Create(m).Error; dbErr != nil {
			return dbErr
		}
		tags := make([]*model.TSchoolTag, 0)
		for _, tagModel := range req.TSchoolTagList {
			tag := new(model.TSchoolTag)
			dbErr := copier.Copy(&tag, tagModel)
			if dbErr != nil {
				return dbErr
			}
			tag.SchoolId = &m.Id
			tag.Id = 0
			tags = append(tags, tag)
		}
		if len(tags) > 0 {
			if dbErr := tx.Model(&model.TSchoolTag{}).CreateInBatches(tags, 100).Error; dbErr != nil {
				return dbErr
			}
		}
		return nil
	})
	if err != nil {
		return nil, err
	}
	return &vo.AddTSchoolRsp{
		Id: m.Id,
	}, nil
}

// Edit 修改学校表
func (s *tSchoolService) Edit(req *vo.EditTSchoolReq) (*vo.EditTSchoolRsp, error) {
	m := new(model.TSchool)
	err := copier.Copy(m, req)
	if err != nil {
		return nil, err
	}
	if err := s.TSchoolRepo.Update(m); err != nil {
		return nil, err
	}
	return &vo.EditTSchoolRsp{
		Id: m.Id,
	}, nil
}

// Del 删除学校表
func (s *tSchoolService) Del(id int64) error {
	return s.TSchoolRepo.Delete(id)
}

func (s *tSchoolService) BatchDel(ids []string) error {
	return s.TSchoolRepo.BatchDelete(ids)
}
